﻿using System;
using System.Collections.Generic;
using Sliver.Core.Event;
using Sliver.Network.Components;
using Sliver.Network.Controller;
using Sliver.Network.WebSocket;
using Sliver.Network.WebSocket.Client;
using WebSocketSharp;

namespace Sliver.Network
{
    public class WebSocketManager : IWebSocketClientListener
    {
        public static WebSocketManager Instance = new WebSocketManager();

        public AbsWebSocketClient WebSocketClient;

        protected WebSocketMessageDispatcher MessageDispatcher;

        protected WebSocketManager()
        {
            Dictionary<string, object> controllers = new Dictionary<string, object>
            {
                // {"lobby", new GameLobbyController()},
                // {"table", new GameTableController()},
                {"game", new GameController()}
            };
            MessageDispatcher = new WebSocketMessageDispatcher(controllers);
        }

        public void InitFake()
        {
            if (WebSocketClient is FakeWebSocketClient) return;
            WebSocketClient = new FakeWebSocketClient();
        }
        
        public void InitWebSocket(Dictionary<string, string> customParams, IWebSocketClientListener listener)
        {
            WebSocketClient client = new WebSocketClient(MessageDispatcher);
            client.AddListener(this);
            if (listener != null) client.AddListener(listener);
            WebSocketClient = client;
            client.Connect(customParams);
        }
        
        public static void SendService(string path, object data = null)
        {
            Instance.Send(WebSocketMessageType.Service, path, data);
        }

        public static void SendInfo(int id, string path, object data)
        {
            Instance.Send(WebSocketMessageType.Info, path, data);
        }

        public static void SendAction(string path, object data, Action callback = null)
        {
            Instance.Send(WebSocketMessageType.Action, path, data, callback);
        }

        public void Send(string type, string path, object data, Action callback = null)
        {
            WebSocketClient.SendMessage(type, path, data, callback);
        }
        
        /// <summary>
        /// Websocket开启，说明房间被建立
        /// </summary>
        public void OnOpen(AbsWebSocketClient client, EventArgs args)
        {
            WebSocketManager.SendInfo(-1, "/connect", "flowerlet");
        }

        public void OnError(AbsWebSocketClient client, ErrorEventArgs args)
        {
        }

        public void OnClose(AbsWebSocketClient client, CloseEventArgs args)
        {
            EventManager.Emit("host_disconnect");
        }

        public void OnReceiveMessage(AbsWebSocketClient client, MessageIn message)
        {
        }
    }
}